<!-- TODO -->
<template>
    <div>
        <!-- header -->
        <el-card class="!border-none" shadow="never">
            <el-alert type="warning" :closable="false" show-icon>
                <template #title>
                    1.订单主状态有待付款，待取货，已完成，已关闭，其中待取货下有2个子状态：待配送、配送中。<br />
                    2.待付款订单取消后则为已关闭。待付款订单支付后则为待配送。待配送订单发货后则为配送中。配送中订单团长取货后则为待取货。待取货订单取货后则为已完成。
                </template>
            </el-alert>
            <el-form ref="formRef" class="mb-[-16px] mt-[15px]" :inline="true" :model="queryParams">
                <el-form-item label="商品名称" prop="name">
                    <el-input
                        class="w-[240px] h-[32px]"
                        @keyup.enter="resetPage"
                        placeholder="请输入商品名称"
                        clearable
                        v-model="queryParams.goods_keys"
                    />
                </el-form-item>
                <el-form-item label="用户ID" prop="name">
                    <el-input
                        class="w-[120px] h-[32px]"
                        placeholder="请输入用户ID"
                        clearable
                        v-model="queryParams.uuid"
                    />
                </el-form-item>
				<el-form-item label="用户搜索" prop="name">
				    <el-input
				        class="w-[150px] h-[32px]"
				        placeholder="请输入手机|昵称搜索"
				        clearable
				        v-model="queryParams.user_keys"
				    />
				</el-form-item>
				<el-form-item label="团长ID搜索" prop="name">
				    <el-input
				        class="w-[150px] h-[32px]"
				        placeholder="请输入团长ID搜索"
				        clearable
				        v-model="queryParams.community_user_id"
				    />
				</el-form-item>
				<el-form-item label="团长ID搜索" prop="name">
				    <el-input
				        class="w-[150px] h-[32px]"
				        placeholder="请输入团长手机|昵称搜索"
				        clearable
				        v-model="queryParams.community_keys"
				    />
				</el-form-item>
				<el-form-item label="订单号搜索" prop="name">
				    <el-input
				        class="w-[240px] h-[32px]"
				        placeholder="请输入订单号"
				        clearable
				        v-model="queryParams.order_no"
				    />
				</el-form-item>
				<el-form-item label="微信支付单号搜索" prop="name">
				    <el-input
				        class="w-[240px] h-[32px]"
				        placeholder="请输入微信支付单号"
				        clearable
				        v-model="queryParams.payment_trade"
				    />
				</el-form-item>
				<el-form-item label="收货手机" prop="name">
				    <el-input
				        class="w-[240px] h-[32px]"
				        placeholder="请输入收货手机号"
				        clearable
				        v-model="queryParams.truck_address_phone"
				    />
				</el-form-item>
				<el-form-item label="订单金额" prop="name">
				    <el-input
				        class="w-[120px] h-[32px]"
				        placeholder="请输入订单金额"
				        clearable
				        v-model="queryParams.amount_real"
				    />
				</el-form-item>
                <el-form-item label="发货方式" prop="name">
                    <el-select
                        placeholder="全部"
                        class="w-[120px] h-[32px]"
                        v-model="queryParams.user_pick_type"
                    >
                        <el-option label="全部" value="" />
                        <el-option label="自提订单" :value="1" />
                        <el-option label="物流订单" :value="2" />
                    </el-select>
                </el-form-item>
				<el-form-item label="退款状态" prop="name">
				    <el-select
				        placeholder="全部"
				        class="w-[120px] h-[32px]"
				        v-model="queryParams.sale_status"
				    >
				        <el-option label="全部" value="" />
				        <el-option label="申请退款" :value="1" />
				        <el-option label="未申请退款" :value="2" />
				    </el-select>
				</el-form-item>
               <el-form-item label="支付方式" prop="name">
                   <el-select
                       placeholder="全部"
                       class="w-[240px] h-[32px]"
                       v-model="queryParams.payment_type"
                   >
                       <el-option label="全部" value="" />
                       <el-option label="礼品券支付" value="payment_type" />
                       <el-option label="积分券兑换" value="balance_red" />
                       <el-option label="微信小程序支付" value="wechat_xcx" />
               		<el-option label="微信公众号支付" value="wechat_gzh" />
               		<el-option label="三方公众号支付" value="tianta_gzh" />
               		<el-option label="VN三方公众号支付" value="vn_gzh" />
               		<el-option label="汇付三方公众号支付" value="hf_gzh" />
               		<el-option label="AD三方公众号支付" value="ad_gzh" />
               		<el-option label="宇燕三方公众号支付" value="yy_gzh" />
                   </el-select>
               </el-form-item>
			   <el-form-item label="下单时间" prop="name">
				<daterange-picker
				    class="w-[385px]"
					value-format="YYYY-MM-DD"
				    v-model:startTime="queryParams.create_at_start_time"
				    v-model:endTime="queryParams.create_at_end_time"
				/>
			   </el-form-item>
			   <el-form-item label="支付时间" prop="name">
			   	<daterange-picker
			   	    class="w-[385px]"
			   		value-format="YYYY-MM-DD"
			   	    v-model:startTime="queryParams.payment_datetime_start_time"
			   	    v-model:endTime="queryParams.payment_datetime_end_time"
					:default="route.query?.time"
			   	/>
			   </el-form-item>
                <el-col>
                    <el-form-item>
                        <el-button type="primary" @click="resetPageNew">查询</el-button>
                        <el-button @click="resetParams">重置</el-button>
						<el-button type="success" @click="exportTable">导出</el-button>
                        <!-- <export-data class="ml-3" :pageSize="pager.size" :method="getOrderPageList"  :param="queryParams" /> -->
                    </el-form-item>
                </el-col>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-tabs class="demo-tabs" v-model="queryParams.status" @tab-click="handleTabclick">
                <el-tab-pane :label="`全部(${pager.status_count.ta || 0})`" :name="''"> </el-tab-pane>
                <el-tab-pane
                    :label="`等待支付(${pager.status_count.t2 || 0})`"
                    :name="2"
                ></el-tab-pane>
                <el-tab-pane
                    :label="`等待发货(${pager.status_count.t4 || 0})`"
                    :name="4"
                ></el-tab-pane>
                <el-tab-pane
                    :label="`等待收货(${pager.status_count.t5 || 0})`"
                    :name="5"
                ></el-tab-pane>
                <el-tab-pane
                    :label="`团长已签收(${pager.status_count.t7 || 0})`"
                    :name="7"
                ></el-tab-pane>
                <el-tab-pane
                    :label="`已完成(${pager.status_count.t9 || 0})`"
                    :name="9"
                ></el-tab-pane>
                <el-tab-pane
                    :label="`售后订单(${pager.status_count.t10 || 0})`"
                    :name="10"
                ></el-tab-pane>
                <el-button
                        @click="unAutoFun('replenish_order', 0)"
                        class="w-[84px] h-[30px] mb-[9px] text-[12px] ml-2"
                        type="success"
                >
                    手动补单
                </el-button>
                <el-button
                        @click="unAutoFun('sucall_order', 0)"
                        class="w-[84px] h-[30px] mb-[9px] text-[12px] ml-2"
                        type="success"
                >
                    手动核销
                </el-button>
                <el-button
                        @click="unAutoFun('for_order', 0)"
                        class="w-[84px] h-[30px] mb-[9px] text-[12px] ml-2"
                        type="success"
                >
                    手动签收
                </el-button>
                <el-button
                        @click="unAutoFun('deliver_order', 0)"
                        class="w-[84px] h-[30px] mb-[9px] text-[12px] ml-2"
                        type="success"
                >
                    手动发货
                </el-button>
                <el-button
                        @click="unAutoFun('sucall_order', 1)"
                        type="primary"
                        class="w-[84px] h-[30px] mb-[9px] text-[12px] ml-2"
                        :disabled="ids.length > 0 ? false : true"
                >
                    一键核销
                </el-button>
                <el-button
                        @click="unAutoFun('for_order', 1)"
                        type="primary"
                        class="w-[84px] h-[30px] mb-[9px] text-[12px] ml-2"
                        :disabled="ids.length > 0 ? false : true"
                >
                    一键签收
                </el-button>
                <el-button
                        @click="unAutoFun('deliver_order', 1)"
                        type="primary"
                        class="w-[84px] h-[30px] mb-[9px] text-[12px] ml-2"
                        :disabled="ids.length > 0 ? false : true"
                >
                    一键发货
                </el-button>
                <el-table
                    size="large"
                    class="mt-[14px]"
                    :data="pager.lists"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="55" />
                    <!-- <el-table-column label="订单编号" prop="sn" min-width="120" /> -->
                    <el-table-column label="用户信息" prop="nickname" min-width="250">
                        <template #default="{ row }">
							<div class="flex" style="align-items: center;">
								<div class="flex mr-[10px]">
								    <el-image
								        :src="row.user.headimg"
								        style="width: 40px; height: 40px; border-radius: 50%"
								    />
								</div>
								<div>
									<div class="flex col-top">
									    <span class="flex-none ">用户ID：</span>
									    <span>{{ row.user.id }}</span>
									</div>
									<div class="flex col-top">
									    <span class="flex-none ">昵称：</span>
									    <span>{{ row.user.username }}</span>
									</div>
									<div class="flex col-top">
									    <span class="flex-none ">手机号：</span>
									    <span>{{ row.user.phone }}</span>
									</div>
								</div>
							</div>



                        </template>
                    </el-table-column>
                    <el-table-column label="商品信息" min-width="250">
                        <template #default="{ row }">
                            <div v-for="(item, index) in row.items" :key="index">
                                <div class="mt-[15px] flex" style="height: 65px" v-if="index < 3">
                                    <el-image
                                        :src="item.goods_cover"
                                        style="width: 58px; height: 58px"
                                        class="flex-none"
                                    />
                                    <el-tooltip :content="item.goods_name" placement="top-start">
                                        <div class="ml-[10px] flex flex-col justify-between">
                                            <span>{{ item.goods_name }}</span>
                                            <span class="text-red"
                                                >￥{{
                                                    `${item.price_selling} x ${item.stock_sales}`
                                                }}</span
                                            >
                                        </div>
                                    </el-tooltip>
                                </div>
                            </div>
                            <!-- <el-button
                                link
                                type="primary"
                                v-if="row.order_goods.length >= 4"
                                @click="moreopen(row.id)"
                            >
                                查看更多<el-icon class="el-icon--right"><arrow-right /></el-icon>
                            </el-button> -->
                        </template>
                    </el-table-column>
                   <!-- <el-table-column label="收货人" prop="contact" min-width="120" />
                    <el-table-column label="团长">
                        <template #default="{ row }">
                            {{ row.teamhead_name + '-' + row.teamhead_real_name }}
                        </template>
                    </el-table-column> -->
                    <el-table-column width="100" label="订单状态">
                        <template #default="{ row }">
                            <span :class="{ 'text-red': row.status_dao_name === '待付款' }">{{
                                row.status_dao_name
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单信息" min-width="280">
						<template #default="{ row }">
						   <div>订单单号：{{row.order_no}}</div>
						   <div v-if="row.order_no_wx">微信支付单号：{{row.order_no_wx}}</div>
						   <div>订单总计：{{row.amount_total}} 元 已支付 {{row.amount_real}} 元</div>
						   <div>下单时间：{{row.create_at}}</div>
						   <div>支付状态：<text class="text-red">{{row.status_name}}</text></div>
						   <div>订单备注：{{row.order_remark}}</div>
						</template>
					</el-table-column>
					<el-table-column label="发货信息" min-width="280">
						<template #default="{ row }">
							<div v-if="row.truck_type==0">无需发货</div>
							<div v-if="row.truck_type==1&&row.is_pick==1">
								<div>自提点地址：{{row.from.address}}</div>
								<div>自提点联系人：{{row.from.name}}</div>
								<div>自提点联系电话：{{row.from.phone}}</div>
								<div>发货状态：自提</div>
							</div>
						   <div v-if="row.truck_type==1&&row.is_pick==2">
								<div>收货信息：{{row.truck.address_name}}{{row.truck.address_phone}}</div>
								<div>收货区域：{{row.truck.address_province}}{{row.truck.address_city}}{{row.truck.address_area}}</div>
								<div>收货地址：{{row.truck.address_content}}</div>
								<div>发货状态：物流</div>
								<div v-if="row.truck.send_datetime">发货时间：{{row.truck.send_datetime}}</div>
						   </div>
						</template>
					</el-table-column>
					<el-table-column label="售后信息" min-width="280">
						<template #default="{ row }">
							<div v-if="row.status==10">
								<div>申请退款时间：{{row.refund_time}}</div>
								<div>退款金额：{{row.refund_real}} </div>
								<div>退款单号：{{row.out_refund_no}}</div>
								<div>退款描述：{{row.sale_remark}}</div>
								<div>退款时间：{{row.sale_time}}</div>
							</div>
							<div v-else>暂无退款</div>
						</template>
					</el-table-column>
                    <el-table-column label="操作" fixed="right" width="240">
                        <template #default="{ row }">
                            <el-button
                                    type="primary"
                                    @click="goDetail(row.order_no)"
                            >
                                详情
                            </el-button>
                            <el-button
                                    type="primary"
                                    @click="goRemark(row.order_no)"
                            >
                                备注
                            </el-button>
                            <el-button
								v-if="['待付款', '售后完成'].indexOf(row.status_dao_name) == -1"
								type="danger"
								@click="returnPay(row.order_no)"
                            >
                                退款
                            </el-button>
							<div v-if="queryParams.status == '5'">
								<el-button
										type="success"
										@click="receivingConfirm(row.id)"
								>
									确认收货
								</el-button>
							</div>
<!--                            <el-button-->
<!--                                type="primary"-->
<!--                                link-->
<!--                                @click="handledeconfirm(0, row.id)"-->
<!--                                v-if="row.order_status_desc === '配送中'"-->
<!--                            >-->
<!--                                确认收货-->
<!--                            </el-button>-->
<!--                            <el-button-->
<!--                                type="primary"-->
<!--                                link-->
<!--                                @click="handledeconfirm(1, row.id)"-->
<!--                                v-if="row.order_status_desc === '待取货'"-->
<!--                            >-->
<!--                                确认取货-->
<!--                            </el-button>-->
<!--                            <el-button-->
<!--                                type="primary"-->
<!--                                link-->
<!--                                @click="handledelivery(row.id)"-->
<!--                                v-if="row.order_status_desc === '待配送'"-->
<!--                            >-->
<!--                                发货-->
<!--                            </el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
            </el-tabs>
            <!-- 分页 -->
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <DetailPopup v-if="detailShow" ref="detailRef" @close="detailShow = false"></DetailPopup>
		<RemarkPopup v-if="remarkShow" ref="remarkRef" @success="submitRemark"  @close="reamarkShow = false" />
        <NumberPopup v-if="numberShow" ref="numberRef" @success="submitNum"  @close="numberShow = false" />
        <MoneyPopup v-if="moneyShow" ref="moneyRef" @success="submitMoney"  @close="moneyShow = false" />
    </div>
</template>

<script lang="ts" setup>
import RemarkPopup from './remark.vue'
import NumberPopup from './number.vue'
import DetailPopup from './detail.vue'
import MoneyPopup from './money.vue'
import { getRoutePath } from '@/router'
// import exportData from '@/components/export-data/index.vue'
const route = useRoute()
import { usePaging } from '@/hooks/usePaging'
import {
	getOrderPageList,
	remark,
	replenish_order,
	sucall_order,
	sucall_order_un,
	for_order,
	for_order_un,
	deliver_order,
	deliver_order_un,
	refund, confirm
} from '@/api/order'
import feedback from '@/utils/feedback'
const queryParams = reactive({
    uuid: '',
    user_keys: '',
	goods_keys:"",
	community_user_id:'',
	community_keys:'',
	order_no:'',
    order_terminal: '', //订单来源
    payment_trade: '', //微信支付单号
	truck_address_phone:'', //收货手机号
    amount_real: '', //订单金额
	user_pick_type:'',//发货方式 默认自提
    sale_status: '', //退款状态
	payment_type:'', //支付方式
    create_at: '', //下单时间
    payment_datetime: '',//支付时间
	payment_datetime_start_time: '',//支付时间
	payment_datetime_end_time: '',//支付时间
    status: '',  //订单状态
	start_time:'',
	end_time:'',
	export: false, // true：导出|false:不导出
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: getOrderPageList,
    params: queryParams
})


console.log(route.query)


// 初始化
if (route.query.time === 'today') {
	const now = new Date();
	const year = now.getFullYear(); // 获取当前年份
	const month = (now.getMonth() + 1).toString().padStart(2, '0');
	const day = now.getDate().toString().padStart(2, '0');
	queryParams.payment_datetime_start_time = `${year}-${month}-${day}`;
	queryParams.payment_datetime_end_time = `${year}-${month}-${day}`;
	queryParams.payment_datetime = `${year}-${month}-${day} - ${year}-${month}-${day}`
	getLists()
} else {
	getLists()
}



const resetPageNew = () => {
	queryParams.create_at = queryParams.create_at_end_time ? `${queryParams.create_at_start_time} - ${queryParams.create_at_end_time}` : null;
	queryParams.payment_datetime = queryParams.payment_datetime_end_time ? `${queryParams.payment_datetime_start_time} - ${queryParams.payment_datetime_end_time}` : null;
	getLists()
}


// 导出
const userStore = useUserStore()
import { urlDownload } from '@/utils/download';
import useUserStore from "@/stores/modules/user";
const exportTable = async () => {
	queryParams.export = true;
	let baseUrl = `/v2/admin.shop.order/getOrderPageList?authorization=${userStore.token}&`;
	Object.entries(queryParams).forEach((res, index) => {
		baseUrl += `${res[0]}=${res[1]}${Object.entries(queryParams).length == index+1 ? '' : '&'}`
	});
	await urlDownload(baseUrl);
	queryParams.export = false;
};

//切换tab栏
const handleTabclick = async () => {
    await nextTick()
    getLists()
}

const ids = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
    ids.value = val.map((item) => {
        return item.id
    })
}

// 手动输入编号
const numberRef = shallowRef<InstanceType<typeof NumberPopup>>();
const numberShow = ref(false);

// 提交编号
const submitNum = (formData: any) => {
    switch (formData.str) {
		case 'replenish_order':  // 手动补单
			replenish_order({payment_trade: formData.goods_code});
			break;
        case 'sucall_order':  // 核销
			sucall_order({goods_code: formData.goods_code});
            break;
        case 'for_order': // 签收
			for_order({goods_code: formData.goods_code});
            break;
        case 'deliver_order':
			deliver_order_un({goods_code: formData.goods_code});
            break;
        default:
            break
    }
};

// 自动和手动
const unAutoFun = async (str: string, type: number) => {
    switch (str) {
		case 'replenish_order':  // 手动补单
			numberShow.value = true;
			await nextTick();
			numberRef.value?.open();
			numberRef.value?.getType(str, type, '商户单号')
			break;
        case 'sucall_order':  // 核销
            if (type) { // 自动
                await sucall_order_un({id: JSON.stringify(ids.value)})
                getLists()
            } else {
                numberShow.value = true;
                await nextTick();
                numberRef.value?.open();
                numberRef.value?.getType(str, type)
            }
            break;
        case 'for_order': // 签收
            if (type) {  // 自动
                await for_order_un({id: JSON.stringify(ids.value)})
                getLists()
            } else {
                numberShow.value = true;
                await nextTick();
                numberRef.value?.open();
                numberRef.value?.getType(str, type)
            }
            break;
        case 'deliver_order':  // 发货
            if (type) {  // 自动
                await deliver_order({id: JSON.stringify(ids.value)})
                getLists()
            } else {
                numberShow.value = true;
                await nextTick();
                numberRef.value?.open();
                numberRef.value?.getType(str, type)
            }
            break;
        default:
            break
    }
}





// 订单详情
const detailRef = shallowRef<InstanceType<typeof DetailPopup>>();
const detailShow = ref(false);
const goDetail = async (order_no: string) => {
    detailShow.value = true;
    await nextTick();
    detailRef.value?.open();
    detailRef.value?.setFormData(order_no)
}


// goDetail('123123')

//
// const handledelivery = async (id?: any) => {
//     try {
//         await feedback.confirm('确定要发货？')
//         await delivery({ ids: typeof id === 'number' ? [id] : ids.value })
//         getLists()
//     } catch (error) {
//         getLists()
//     }
// }
// // //确认收货/取货
// const handledeconfirm = async (type: any, id?: any) => {
//     await feedback.confirm(`确认要${type == 0 ? '收货' : '取货'}?`)
//     type == 0
//         ? await confirmReceipt({ ids: id ? [id] : ids.value })
//         : await confirmPickup({ ids: id ? [id] : ids.value })
//     getLists()
// }
//退款
const moneyRef = shallowRef<InstanceType<typeof DetailPopup>>();
const moneyShow = ref(false);
const returnPay = async (order_no: any) => {
    moneyShow.value = true;
    await nextTick();
    moneyRef.value?.open();
    moneyRef.value?.setFormData({order_no})
}
const submitMoney = async (formData: any) => {
    await refund(formData)
    getLists()
};


// 备注
const remarkRef = shallowRef<InstanceType<typeof RemarkPopup>>();
const remarkShow = ref(false);
const goRemark = async (order_no: any) => {
    remarkShow.value = true;
    await nextTick();
    remarkRef.value?.open();
    remarkRef.value?.setFormData({order_no})
}
// 提交备注
const submitRemark = async (formData: any) => {
    await remark(formData)
    getLists()
};


// 确认收货
const receivingConfirm = async (id: number) => {
    await feedback.confirm('确认已收货?');
    await confirm({ id });
    getLists()
}

</script>
<style lang="scss" scope>
//TODO
.el-alert--warning.is-light {
    background-color: rgba(246, 248, 255, 1);
    color: rgba(64, 115, 250, 1);
}
.text-red {
    color: red;
}
.el-button {
	margin: 5px 0
}
</style>
